package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.VideoEnabledWebView;
import com.le123.ysdq.R;

import java.util.Formatter;
import java.util.Locale;
import java.util.Timer;

/**
 * Created by biandi on 2017/3/7.
 */

public class WebVideoController implements View.OnClickListener,SeekBar.OnSeekBarChangeListener,View.OnTouchListener{

    private Activity mActivity;
    private VideoEnabledWebView mWebView;
    protected PlayerTimer mPlayerTimer;

    private View lyScreen;
    private RelativeLayout lyHead;
    private LinearLayout lyVideoControl;
    private LinearLayout lyPlay;
    private ImageView imgPlay;
    private TextView tvTotalTime;
    private TextView tvCurrentTime;
    private TextView tvTitle;
    private TextView tvUrl;
    private SeekBar seekBar;
    private ImageView imgBack;

    private boolean mIsPause = false;
    private int mDuration; // 视频总时长
    private int mCurrentTime = 0; // 当前播放时长
    private final int PLAY_SEEKBAR_MAX = 1000; //播放进度条的最大值
    private final int MSG_UPDATE_TOTAL_TIME = 1000; //播放进度条的最大值
    private final int MSG_WHAT_GET_VIDEO_SRC = 1001;
    private final int MSG_WHAT_AUTO_PLAY = 1002;
    private final int MSG_GET_VIDEO_SRC_DELAY_TIME = 300;
    private final int MAX_INTERVAL_COUNT = 20;
    private String mUrl;
    private String mTitle;
    private boolean mIsIQiYi = false;
    private boolean mIsVideoReady = false;
    private boolean mIsVideoFullScreen = false;
    private int mIntervalCount = 0;
    private WebVideoPlayerGestureHandle mGestureHandle;

    public WebVideoController(Activity activity, VideoEnabledWebView webView,String url,String title,boolean isIQiYi) {
        mActivity = activity;
        mWebView = webView;
        mUrl = url;
        mTitle = title;
        mIsIQiYi = isIQiYi;
        mWebView.setJavascriptInterface(new JavascriptInterface());
    }

    private void initView() {
        imgPlay = (ImageView) mActivity.findViewById(R.id.img_play);
        lyPlay = (LinearLayout) mActivity.findViewById(R.id.ly_play);
        imgBack = (ImageView) mActivity.findViewById(R.id.img_back);
        tvTotalTime = (TextView) mActivity.findViewById(R.id.tv_totaltime);
        tvCurrentTime = (TextView) mActivity.findViewById(R.id.tv_currtime);
        seekBar = (SeekBar) mActivity.findViewById(R.id.full_play_seekbar);
        lyScreen = (RelativeLayout) mActivity.findViewById(R.id.layout_screen);
        lyVideoControl = (LinearLayout) mActivity.findViewById(R.id.layout_web_video_control);
        lyHead = (RelativeLayout) mActivity.findViewById(R.id.layout_head);
        tvTitle = (TextView) mActivity.findViewById(R.id.tv_title);
        tvUrl = (TextView) mActivity.findViewById(R.id.tv_url);
        if (null == mGestureHandle) {
            mGestureHandle = new WebVideoPlayerGestureHandle(mActivity, mHandler, this, lyScreen);
        }

        lyScreen.setOnClickListener(this);
        lyScreen.setOnTouchListener(this);
        lyPlay.setOnClickListener(this);
        imgBack.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(this);
        seekBar.setMax(PLAY_SEEKBAR_MAX);
        seekBar.setProgress(0);
        seekBar.setSecondaryProgress(0);
    }

    public void prepare() {
        initView();
        getFirstTotalTime();
        startPlayerTimer();
        getTotalTime();
        getVideoTitle();
        setUrlAndTitle(mUrl, mTitle);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.layout_screen:
                if (null != mGestureHandle) {
                    mGestureHandle.handleGestureSlide(event);
                }
                break;
            default:
                break;
        }
        return false;
    }

    public class JavascriptInterface {
        @android.webkit.JavascriptInterface
        public void onGetDuration(int time, String title) {
            mDuration = time;
            mTitle = title;
            mHandler.sendEmptyMessage(MSG_UPDATE_TOTAL_TIME);
        }

        @android.webkit.JavascriptInterface
        public void isPause(boolean isPause) {
            mIsPause = isPause;
            if (isPause) {
                imgPlay.setBackgroundResource(R.drawable.videoplayer_play_selector);
            } else {
                imgPlay.setBackgroundResource(R.drawable.videoplayer_pause_selector);
            }
        }

        @android.webkit.JavascriptInterface
        public void onGetCurrentTime(int time) {
            mCurrentTime = time;
        }

        @android.webkit.JavascriptInterface
        public void onGetVideoTitle(String title) {
            tvTitle.setText(title);
        }

        @android.webkit.JavascriptInterface
        public void onGetFirstTime(int time, String title) {
            mDuration = time;
            mTitle = title;
            mHandler.sendEmptyMessage(MSG_UPDATE_TOTAL_TIME);
        }

        @android.webkit.JavascriptInterface
        public void onVideoReady() {
            if (!mIsVideoReady && mActivity != null && mActivity instanceof PlayActivityFroWebView) {
                mHandler.removeMessages(MSG_WHAT_GET_VIDEO_SRC);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(MoviesConstant.ONEPOINT_TAG.equals(mTitle)){
                            if(NetWorkTypeUtils.TYPE_WIFI == NetWorkTypeUtils.reportNetType(mActivity)){
                                mHandler.sendEmptyMessage(MSG_WHAT_AUTO_PLAY);
                                mHandler.sendEmptyMessageDelayed(MSG_WHAT_AUTO_PLAY, MSG_GET_VIDEO_SRC_DELAY_TIME);
                                mHandler.sendEmptyMessageDelayed(MSG_WHAT_AUTO_PLAY, 2 * MSG_GET_VIDEO_SRC_DELAY_TIME);
                            }
                        }else{
                            addVideoOnPlayListener();
                        }
                    }
                });
                mIsVideoReady = true;
            }
        }
        @android.webkit.JavascriptInterface
        public void onUserStartPlay() {
            if (!mIsVideoFullScreen) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 全屏播放
                        onFullScreen();
                        if (mIsIQiYi) {
                            PlayActivityFroWebView activity = (PlayActivityFroWebView) mActivity;
                            activity.setStatistics();
                        }

                    }
                });
                mIsVideoFullScreen = true;
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_play:
                onPlay();
                break;
            case R.id.layout_screen:
                if (lyVideoControl.getVisibility() == View.GONE) {
                    dissMissMediaControll(View.VISIBLE);
                    mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                            Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                } else {
                    dissMissMediaControll(View.GONE);
                    mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
                }
                break;
            case R.id.img_back:
                stopPlayerTimer();
                mActivity.finish();
//                mIsVideoFullScreen = false;
//                cancelFullScreen();
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int mUserDragTime = (mDuration * seekBar.getProgress()) / PLAY_SEEKBAR_MAX;
        setCurrentTime(mUserDragTime);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                Utils.MEDIA_CONTROLLER_DISMISS_TIME);
        int seekBarProgress = seekBar.getProgress();
        int time = (mDuration * seekBarProgress / PLAY_SEEKBAR_MAX);
        mCurrentTime = time;
        onSeekTo(time);
    }

    /**
     * 全屏播放
     */
    public void onFullScreen() {
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("videoElement.webkitEnterFullscreen();");
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void onStartPlay() {
        final StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("videoElement.play();");
        mWebView.loadUrl(jsBuilder.toString());
    }

    /**
     * 添加video标签开始播放的监听
     *
     */
    public void addVideoReadyListener() {
        mIsVideoReady = false;
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("window.onload = function() {");
        jsBuilder.append("_VideoEnabledWebView.onVideoReady();");
        jsBuilder.append("};");
        mHandler.removeMessages(MSG_WHAT_GET_VIDEO_SRC);
        mHandler.sendEmptyMessageDelayed(MSG_WHAT_GET_VIDEO_SRC, MSG_GET_VIDEO_SRC_DELAY_TIME);
        if(!MoviesConstant.ONEPOINT_TAG.equals(mTitle)) {
            mWebView.loadUrl(jsBuilder.toString());
        }
    }

    /**
     * 取消全屏
     */
    public void cancelFullScreen() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("document.webkitCancelFullScreen();");
        mWebView.loadUrl(jsBuilder.toString());
    }

    /**
     * 隐藏video标签自带的控制栏
     */
    public void disableVideoControls() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        //jsBuilder.append("videoElement.controls=false;");
//        jsBuilder.append("videoElement.removeAttribute('controls');");
        //jsBuilder.append("videoElement.load();");
        jsBuilder.append("video::-webkit-media-controls-panel{");
        jsBuilder.append("display:none !important;}");
        mWebView.loadUrl(jsBuilder.toString());
    }

    /**
     * 点击播放按钮事件
     */
    public void addVideoOnPlayListener() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("videoElement.addEventListener('play', function() {");
        jsBuilder.append("_VideoEnabledWebView.onUserStartPlay();");
        jsBuilder.append("});");
        mWebView.loadUrl(jsBuilder.toString());
    }

    private void getVideoSrc() {
        mIntervalCount++;
        if (mIntervalCount > MAX_INTERVAL_COUNT) {
            return;
        }
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("if (videoElement !== undefined) {");
        jsBuilder.append("var src = videoElement.src;");
        jsBuilder.append("if (src !== undefined && src !== null && src !== '') {");
        jsBuilder.append("_VideoEnabledWebView.onVideoReady();");
        jsBuilder.append("}");
        jsBuilder.append("}");
        mWebView.loadUrl(jsBuilder.toString());
        mHandler.sendEmptyMessageDelayed(MSG_WHAT_GET_VIDEO_SRC, MSG_GET_VIDEO_SRC_DELAY_TIME);
    }

    private void onPlay() {
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("var isPaused = videoElement.paused;");
        jsBuilder.append("if (isPaused) {");
        jsBuilder.append("videoElement.play();");
        jsBuilder.append("} else {");
        jsBuilder.append("videoElement.pause();");
        jsBuilder.append("}");
        jsBuilder.append("_VideoEnabledWebView.isPause(videoElement.paused);");
        mWebView.loadUrl(jsBuilder.toString());
    }

    /**
     *
     * @param time 单位秒
     */
    public void onSeekTo(int time) {
        String jsStr = "videoElement.currentTime = " + time + ";";
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append(jsStr);
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void getTotalTime() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("videoElement.addEventListener('durationchange', function() {");
        jsBuilder.append("_VideoEnabledWebView.onGetDuration(videoElement.duration,document.title);");
        jsBuilder.append("});");
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void getCurrentTime() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("_VideoEnabledWebView.onGetCurrentTime(videoElement.currentTime);");
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void getFirstTotalTime() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("_VideoEnabledWebView.onGetFirstTime(videoElement.duration,document.title);");
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void getVideoTitle() {
        StringBuilder jsBuilder = new StringBuilder("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append("_VideoEnabledWebView.onGetVideoTitle(document.title);");
        mWebView.loadUrl(jsBuilder.toString());
    }

    public void setCurrentVolume(String volumeIndex) {
        String jsStr = "videoElement.volume = " + volumeIndex + ";";
        StringBuilder jsBuilder = new StringBuilder();
        jsBuilder.append("javascript:");
        jsBuilder.append("var videoElement = document.getElementsByTagName('video')[0];");
        jsBuilder.append(jsStr);
        mWebView.loadUrl(jsBuilder.toString());
    }

    /**
     * 获取总时长
     * @return
     */
    public int getDuration() {
        return mDuration;
    }

    public int getCurrentPosition() {
        return mCurrentTime;
    }

    private void setCurrentTime(int time) {
        tvCurrentTime.setText(toStringTime(time));
    }

    private void setTotalTime(int time) {
        tvTotalTime.setText(toStringTime(time));
    }

    public void setUrlAndTitle(String url,String title) {
        tvTitle.setText(!TextUtils.isEmpty(title)? title:"");
        tvUrl.setText(!TextUtils.isEmpty(url)? url:"");
    }

    public void setVideoReady(boolean isReady) {
        mIsVideoReady = isReady;
    }


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                // 控制栏消失
                case Utils.DISSMISS_MEDIACONTROLLER:
                    dissMissMediaControll(View.GONE);
                    break;
                // 刷新SeekBar
                case Utils.PROGRESS_CHANGE:
                    getCurrentTime();
                    refreshPlaySeekBar();
                    break;
                case MSG_UPDATE_TOTAL_TIME:
                    tvTotalTime.setText(toStringTime(mDuration));
                    tvTitle.setText(mTitle);
                    break;
                case MSG_WHAT_GET_VIDEO_SRC:
                    getVideoSrc();
                    break;
                case Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW:
                    if (null != mGestureHandle) {
                        mGestureHandle.dismissGesturePopupWindow();
                    }
                    mHandler.sendEmptyMessageDelayed(
                            Utils.DISSMISS_MEDIACONTROLLER,
                            Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                    break;
                case MSG_WHAT_AUTO_PLAY:
                    onStartPlay();
                    break;
            }
        }
    };

    private void dissMissMediaControll(int flag) {
        lyVideoControl.setVisibility(flag);
        lyHead.setVisibility(flag);
    }

    public static String toStringTime(int time) {
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        try {
            if (time <= 0) {
                time = 0;
            }
            int totalSeconds = time;
            int seconds = totalSeconds % 60;
            int minutes = totalSeconds / 60;
            formatBuilder.setLength(0);
            String currtime = formatter.format("%02d:%02d", minutes, seconds)
                    .toString();
            return currtime;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            formatter.close();
        }
        return null;
    }

    /**
     * 开启计时器，秒刷新界面
     */
    protected void startPlayerTimer() {
        // 当前不是暂停状态并且播放器已经准备好了才开始刷新页面
        if (!mIsPause) {
            stopPlayerTimer();
            if (mPlayerTimer == null) {
                mPlayerTimer = new PlayerTimer(mHandler, Utils.PROGRESS_CHANGE);
                Timer m_musictask = new Timer();
                m_musictask.schedule(mPlayerTimer, 0, 1000);
            }
        }
    }

    /**
     * 停止播放器计时
     */
    public void stopPlayerTimer() {
        try {
            if (mPlayerTimer != null) {
                mPlayerTimer.cancel();
                mPlayerTimer = null;
            }
            if (null != mHandler && mHandler.hasMessages(Utils.JUDGE_BUFFER)) {
                mHandler.removeMessages(Utils.JUDGE_BUFFER);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void refreshPlaySeekBar() {
        long progress = mDuration <= 0 ? 0 : (PLAY_SEEKBAR_MAX
                * mCurrentTime / mDuration);
        seekBar.setProgress((int) progress);
        String currTimeStr = toStringTime(mCurrentTime);
        if (!TextUtils.isEmpty(currTimeStr)) {
            tvCurrentTime.setVisibility(View.VISIBLE);
            tvCurrentTime.setText(currTimeStr);
        } else {
            tvCurrentTime.setVisibility(View.GONE);
        }
    }
}
